package com.vichat.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.vichat.common.cache.LocalCacher;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.constant.I18nConstant;
import com.vichat.common.exception.ViChatException;
import com.vichat.common.util.*;
import com.vichat.common.vo.Grid;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.res.entity.ResEvent;
import com.vichat.res.service.IResService;
import com.vichat.user.cache.StaticDataCache;
import com.vichat.user.entity.*;
import com.vichat.user.service.ISystemMessageService;
import com.vichat.user.service.IUserCcsService;
import com.vichat.user.service.IUserService;
import com.vichat.user.vo.RequestParamsVO;
import com.vichat.user.vo.SysParamsVO;
import com.vichat.user.vo.SystemMessageVO;
import com.vichat.user.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by ranjx on 2017/11/20.
 */
@Controller
@RequestMapping("/userApi")
public class UserApiController {
    private static Logger logger = LoggerFactory.getLogger(UserApiController.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserCcsService ccsService;
    @Autowired
    StaticDataCache staticDataCache;
    @Autowired
    private ISystemMessageService systemMessageService;
    @Autowired
    private IResService resService;

    /**
     * 系统参数接口
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/getSystemInfo")
    @ResponseBody
    public Json getSystemInfo(@RequestBody HashMap params) throws IOException {
        Json json = new Json();
        try {
            String appname = (String) params.get("appname");
            HashMap systemInfo = new HashMap();
            SysStaticData httpServer = staticDataCache.getValue("HttpServer", appname);
            if (httpServer != null) {
                systemInfo.put("HttpServer", httpServer.getCodeName());
            }
            SysStaticData proxyServer = staticDataCache.getValue("ProxyServer", appname);
            if (proxyServer != null) {
                systemInfo.put("ProxyServer", proxyServer.getCodeName());
            }

            SysStaticData mediaServer = staticDataCache.getValue("MediaServer", appname);
            if (mediaServer != null) {
                systemInfo.put("MediaServer", proxyServer.getCodeName());
            }

            json.setObj(systemInfo);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     * 获取组织结构接口
     *
     * @param paramsVO
     * @return
     * @throws IOException
     */
    @RequestMapping("/getOrgs")
    @ResponseBody
    public Grid getOrgs(@RequestBody RequestParamsVO paramsVO) throws Exception {
        Grid grid = new Grid();
        try {


            if (NumberUtils.isNull(paramsVO.getVersion())) {
                throw new Exception("version is required");
            }
            if (NumberUtils.isNullOrZero(paramsVO.getPage())) {
                throw new Exception("page is required");
            }
            if (NumberUtils.isNullOrZero(paramsVO.getRows())) {
                throw new Exception("size is required");
            }
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("uid is required");
            }
            if (StringUtils.isEmpty(paramsVO.getToken())) {
                throw new Exception("token is required");
            }
            String token = AES.decrypt(paramsVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(paramsVO.getUid()))) {
                throw new Exception("token is illegal");
            }


            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }
            UserOrg queryBean = new UserOrg();
            queryBean.setPartyId(userBasicFDB.getPartyId());
            queryBean.setVersion(paramsVO.getVersion());
            PageFilter pf = new PageFilter();
            pf.setPage(paramsVO.getPage());
            pf.setLimit(paramsVO.getRows());
            List<UserOrg> orgs = userService.queryUserOrgsApi(queryBean, pf);
            long count = userService.countUserOrgsApi(queryBean);
            grid.setRows(orgs);
            grid.setTotal(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
        }


        return grid;
    }

    /**
     * 获取用户信息
     *
     * @param paramsVO
     * @return
     * @throws IOException
     */
    @RequestMapping("/getUsers")
    @ResponseBody
    public Grid getUsers(@RequestBody RequestParamsVO paramsVO) throws Exception {
        Grid grid = new Grid();
        try {


            if (NumberUtils.isNull(paramsVO.getVersion())) {
                throw new Exception("version is required");
            }
            if (NumberUtils.isNullOrZero(paramsVO.getPage())) {
                throw new Exception("page is required");
            }
            if (NumberUtils.isNullOrZero(paramsVO.getRows())) {
                throw new Exception("size is required");
            }
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("uid is required");
            }
            if (StringUtils.isEmpty(paramsVO.getToken())) {
                throw new Exception("token is required");
            }
            String token = AES.decrypt(paramsVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(paramsVO.getUid()))) {
                throw new Exception("token is illegal");
            }
            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }
            UserBasic queryBean = new UserBasic();
            queryBean.setPartyId(userBasicFDB.getPartyId());
            queryBean.setVersion(paramsVO.getVersion());
            PageFilter pf = new PageFilter();
            pf.setPage(paramsVO.getPage());
            pf.setLimit(paramsVO.getRows());
            pf.setSort("version");
            pf.setOrder("asc");
            List<UserVO> users = userService.queryApiUserBasics(queryBean, pf);
            long count = userService.countUserBasics(queryBean,false);
            grid.setRows(users);
            grid.setTotal(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
        }


        return grid;
    }


    /**
     * 获取APP版本号
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/getAppVer")
    @ResponseBody
    public Json getAppVer(@RequestBody RequestParamsVO paramsVO) throws IOException {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("缺少参数UID");
            }
            if (StringUtils.isBlank(paramsVO.getAppCode())) {
                throw new Exception("appCode不能为空");
            }
            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("没有该用户信息，请确认UID参数");
            }
            Map objMap = new HashMap<>();
            int version = 0;
            List<SysStaticData> sysStaticDatas = LocalCacher.getMulti(StaticDataCache.cacheId(), "AppVer", SysStaticData.class);
            if (!sysStaticDatas.isEmpty()) {
                for (SysStaticData sysStaticData : sysStaticDatas) {
                    if (sysStaticData.codeName.equals(paramsVO.getAppCode())) {
                        version = Integer.parseInt(sysStaticData.getCodeValue());
                    }
                }
            }
            objMap.put("version", version);
            json.setObj(objMap);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     * 获取APP版本号-企业服务码
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/getAppVerBySC")
    @ResponseBody
    public Json getAppVerBySC(@RequestBody HashMap paramsVO) throws IOException {
        Json json = new Json();
        try {

            if (!paramsVO.containsKey("packageName")) {
                throw new Exception("packageName can not be empty");
            }
            HashMap result = new HashMap();
            String packageName = (String) paramsVO.get("packageName");
            int currentVersion = 0;

            AppVersionFile file = ccsService.getStartAppVersionFileByPkgName(packageName);
            if (file != null) {
                SysStaticData appUpdateUrl = staticDataCache.getValue("APP_URL", "-1");
                String httpUrl = appUpdateUrl.getCodeName();
                result.put("versionCode", file.getVersionCode());
                result.put("version", file.getVersionName());
                result.put("appUrl", httpUrl);
            }
            json.setObj(result);
            json.setSuccess(true);
            json.setCode(1);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }


    /**
     * @param
     * @return
     * @throws
     * @Title: changePwd
     * @Description: 修改密码
     */
    @RequestMapping("/changePwd")
    @ResponseBody
    public Json changePwd(@RequestBody RequestParamsVO paramsVO) {
        Json json = new Json();
        String oldPwd = paramsVO.getOldPwd();
        String newPwd = paramsVO.getNewPwd();
        try {
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("缺少参数UID");
            }
            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("用户信息异常");
            }
            oldPwd = Md5Util.Md5Encode(oldPwd, null);
            oldPwd = Md5Util.Md5Encode(oldPwd, null);
            if (!StringUtils.equals(oldPwd, userBasicFDB.getPassword())) {
                throw new Exception("旧密码输入错误，请重新输入");
            } else {
                newPwd = Md5Util.Md5Encode(newPwd, null);
                newPwd = Md5Util.Md5Encode(newPwd, null);
                userBasicFDB.setPassword(newPwd);
                userService.updUserPwd(userBasicFDB);
                userService.updateUserBasicVersion(userBasicFDB.getUid());
                json.setSuccess(true);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
        }
        return json;
    }


    /**
     * 获取个人资料信息
     *
     * @param paramsVO
     * @return
     */
    @RequestMapping("/getMyInfo")
    @ResponseBody
    public Json getMyInfo(@RequestBody RequestParamsVO paramsVO) throws Exception {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("uid is required");
            }

            String token = AES.decrypt(paramsVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(paramsVO.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }
            json.setObj(userBasicFDB);
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
        }

        return json;
    }

    @RequestMapping("/markMessageReaded")
    @ResponseBody
    public Json markMessageReaded(@RequestBody SystemMessageVO paramsVO) {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("uid is required");
            }

            String token = AES.decrypt(paramsVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(paramsVO.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }

            if(paramsVO.getMsgIds() != null && !paramsVO.getMsgIds().isEmpty()){
                for (long msgId:paramsVO.getMsgIds()){
                    SystemMessage systemMessageFDB = systemMessageService.querySystemMessageByMsgId(msgId);
                    if(systemMessageFDB != null){
                        systemMessageFDB.setIsReceive(1L);
                        systemMessageFDB.setIsRead(1L);
                        systemMessageService.saveSystemMessage(systemMessageFDB);
                    }
                }
            }

            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
        }
        return json;
    }

    @RequestMapping("/getUnReadMessage")
    @ResponseBody
    public Grid getUnReadMessage(@RequestBody SystemMessageVO paramsVO) {
        Grid grid = new Grid();
        try {
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("uid is required");
            }

            String token = AES.decrypt(paramsVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(paramsVO.getUid()))) {
                throw new Exception("token is illegal");
            }

            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("User Data Error");
            }
            SystemMessage queryBean = new SystemMessage();
            queryBean.setUid(userBasicFDB.getUid());
            queryBean.setIsRead(0L);
            PageFilter pageFilter = new PageFilter();
            pageFilter.setPage(1);
            pageFilter.setRows(500);
            List<SystemMessage> systemMessages = systemMessageService.querySystemMessage(queryBean,pageFilter);
            grid.setRows(systemMessages);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 获取执法取证
     *
     * @param paramsVO
     * @return
     * @throws Exception
     */
    @RequestMapping("/getResEvent")
    @ResponseBody
    public Grid getResEventToEvidence(@RequestBody RequestParamsVO paramsVO) throws Exception {
        Grid grid = new Grid();

        try {
            if (NumberUtils.isNullOrZero(paramsVO.getPage())) {
                throw new Exception("page is required");
            }
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("uid is required");
            }
            if (NumberUtils.isNullOrZero(paramsVO.getRows())) {
                throw new Exception("size is required");
            }
            if (StringUtils.isEmpty(paramsVO.getToken())) {
                throw new Exception("token is required");
            }
            String token = AES.decrypt(paramsVO.getToken());
            Properties properties = StringToPropertiesConverter.convert(token.replaceAll(",", "\n"));
            String uidInToken = properties.getProperty("uid");
            if (!StringUtils.equals(uidInToken, String.valueOf(paramsVO.getUid()))) {
                throw new Exception("token is illegal");
            }
            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("非法用户ID请求");
            }

            PageFilter pageFilter = new PageFilter();
            pageFilter.setPage(paramsVO.getPage());
            pageFilter.setRows(paramsVO.getRows());
            ResEvent queryBean = new ResEvent();
            queryBean.setEvtType(GlobalConstant.EVT_TYPE_EVIDENCE);
            queryBean.setUid(userBasicFDB.getUid());
            queryBean.setPartyId(userBasicFDB.getPartyId());
            queryBean.setRptUid(userBasicFDB.getUid());
            queryBean.setRptOrgCode(userBasicFDB.getOrgCode());
            queryBean.setRemindUids(String.valueOf(userBasicFDB.getUid()));
            List<ResEvent> resEventList = resService.queryResEvent(queryBean, pageFilter);
            if (resEventList != null) {
                for (ResEvent resEvent : resEventList) {
                    if (NumberUtils.isNotNullOrZero(resEvent.getRptOrgId())) {
                        resEvent.setRptOrgName(RedisHelper.getOrgName(resEvent.getRptOrgId()));
                    }
                    if (NumberUtils.isNotNullOrZero(resEvent.getRptUid())) {
                        resEvent.setRptUserName(RedisHelper.getUname(resEvent.getRptUid()));
                    }

                    if (StringUtils.isNotBlank(resEvent.getRemindUids())) {
                        String userNames = UserUtil.getUserNamesByJson(resEvent.getRemindUids());
                        resEvent.setRemindUserName(userNames);
                    }
                }
            }
            long count = resService.countResEvent(queryBean);

            grid.setData(resEventList);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
        }
        return grid;
    }

}
